package com.guigu.qingcheng.controller;

import com.guigu.common_util.pojo.utils.JwtUtils;
import com.guigu.qingcheng.service.CartService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("/wxpay")
public class WxPayController {

    @Autowired
    private CartService cartService;

    @GetMapping("/createNative")
    public Map createNative(HttpServletRequest request, String orderId){
        String username = JwtUtils.getMemberIdByJwtToken2(request);
        String notifyUrl = "http://qingcheng.easy.echosite.cn/wxpay/notify";
        System.out.println(cartService.createNative(orderId,username,notifyUrl));
        return cartService.createNative(orderId,username,notifyUrl);
    }

    /**
     * 回调
     */
    @RequestMapping("/notify")
    public Map notifyLogic(HttpServletRequest request){
        System.out.println("支付成功回调。。。。");
        InputStream inStream;
        try {
            inStream = request.getInputStream();
            ByteArrayOutputStream outSteam = new ByteArrayOutputStream();
            byte[] buffer = new byte[1024];
            int len = 0;
            while ((len = inStream.read(buffer)) != -1) {
                outSteam.write(buffer, 0, len);
            }
            outSteam.close();
            inStream.close();
            String result = new String(outSteam.toByteArray(), "utf-8");
            cartService.notifyLogic(result);
            System.out.println(result);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return new HashMap();
    }

}
